package com.shujia.kafka

import org.apache.kafka.clients.consumer.{ConsumerRecord, ConsumerRecords, KafkaConsumer}

import java.util
import java.util.Properties

object Demo3Consumer {
  def main(args: Array[String]): Unit = {
    /**
     * 2、建立链接
     */
    val properties = new Properties()

    //kafka集群列表
    properties.setProperty("bootstrap.servers", "master:9092,node2:9092,node2:9092")

    //key 和value 反序列化的类
    properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")

    //设置消费者组
    //一条数据在一个组内只被消费一次
    properties.setProperty("group.id", "Demo3Consumer6")


    /**
     * earliest
     * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，从头开始消费
     * latest  默认
     * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，消费新产生的数据
     * none
     * topic各分区都存在已提交的offset时，从offset后开始消费；只要有一个分区不存在已提交的offset，则抛出异常
     *
     */

    properties.setProperty("auto.offset.reset", "earliest")


    //创建消费者
    val consumer = new KafkaConsumer[String, String](properties)

    //订阅topic
    val topics = new util.ArrayList[String]()
    topics.add("clazz_num")
    consumer.subscribe(topics)

    while (true){

      println("消费数据")

      //消费数据
      val consumerRecords: ConsumerRecords[String, String] = consumer.poll(100)

      //获取一个迭代器
      val recordIter: util.Iterator[ConsumerRecord[String, String]] = consumerRecords.iterator()

      //判断是否有下一行
      while (recordIter.hasNext) {

        //读取下一行
        val record: ConsumerRecord[String, String] = recordIter.next()

        //解析数据
        val topic: String = record.topic()
        val partition: Int = record.partition()
        val offset: Long = record.offset()
        val ts: Long = record.timestamp()
        val key: String = record.key()
        val value: String = record.value()

        println(s"$topic\t$partition\t$offset\t$ts\t$key\t$value")
      }


    }


    //关联链接
    consumer.close()
  }

}
